import React, { Component } from "react";

import { Flex, Toast } from "antd-mobile";
import styles from "./index.module.scss";

import { getCurrentCity, API } from "../../utils";

// import {
//   List,
//   AutoSizer,
//   WindowScroller,
//   InfiniteLoader
// } from "react-virtualized";

import List from 'react-virtualized/dist/commonjs/List'
import AutoSizer from 'react-virtualized/dist/commonjs/AutoSizer'
import WindowScroller from 'react-virtualized/dist/commonjs/WindowScroller'
import InfiniteLoader from 'react-virtualized/dist/commonjs/InfiniteLoader'

//导入搜索导航栏
import SearchHeader from "../../components/SearchHeader";
import Sticky from "../../components/Sticky";
import HouseItem from "../../components/HouseItem";
import NoHouse from "../../components/NoHouse";

// 导入条筛选栏组件
import Filter from "./components/Filter";

const ROW_HEIGHT = 120;

export default class HouseList extends Component {
  state = {
    cityName: "",
    //房源数据列表的数据
    list: [],
    // 房源数量
    count: 0,
    // 是否完成加载
    isLoaded: false
  };

  



  async componentDidMount() {
    const { label, value } = await getCurrentCity();
    this.setState({
      cityName: label
    });

    this.cityId = value;

    this.onFilter({});
  }
  
  // 卸载阶段  为链结局内存泄漏问题
  componentWillUnmount() {
    this.setState = (state, callback) => {
      // console.log(state,callback);  
      return
    }
  }

  // 获取房源数据
  onFilter = async filters => {
    // 每次重新筛选数据是都让页面回到最顶部
    window.scrollTo(0, 0);
    this.filters = filters;

    // 开启loading 效果
    Toast.loading("加载中...", 0);
    //  获取所有的房屋性息
    const res = await API.get("/houses", {
      params: {
        ...filters,
        cityId: this.cityId
      }
    });
    const { list, count } = res.data.body;
    // 手动关闭 loading
    Toast.hide();
    if (count !== 0) {
      // 展示获取到的房源数量
      Toast.info(`共找到${count}套房源`, 1.5);
    }
    this.setState({
      list,
      count,
      // 表示数据加载完成
      isLoaded: true
    });
  };

  // 渲染房源列表结构
  rowRenderer = ({
    key,
    index, // 索引号
    style // 表示给每一行设置的样式（用来给每一行定位）！！！ 注意： 必须要给每一行设置style！！！
  }) => {
    // console.log(this.state.list);
    const item = this.state.list[index];
    if (!item) {
      return (
        <div key={key} style={style}>
          <div className={styles.loading} />
        </div>
      );
    }

    return (
      <div key={key} style={style}>
        <HouseItem {...item} />
      </div>
    );
  };

  // 判断列表中的行数据是否加载完成
  isRowLoaded = ({ index }) => {
    return !!this.state.list[index];
  };

  // 在滚动时，自动加载更多的数据
  loadMoreRows = ({ startIndex, stopIndex }) => {
    return new Promise(async resolve => {
      const res = await API.get("/houses", {
        params: {
          ...this.filter,
          cityId: this.cityId,
          // 分页参数
          start: startIndex,
          end: stopIndex
        }
      });
      const { list, count } = res.data.body;
      this.setState({
        list: [...this.state.list, ...list],
        count
      });
      // 在发送请求获取数据后，来完成Promise
      resolve();
    });
  };

  renderHouseList() {
    const { count,isLoaded} = this.state;
    if(isLoaded && count===0){
      return <NoHouse>没有找到房源，请您换个搜索条件吧~</NoHouse>
    }
    
    return (
      <div className={styles.houseItems}>
        <InfiniteLoader
          isRowLoaded={this.isRowLoaded}
          loadMoreRows={this.loadMoreRows}
          rowCount={count}
        >
          {({ onRowsRendered, registerChild }) => (
            <WindowScroller>
              {({ height, isScrolling, scrollTop }) => (
                <AutoSizer>
                  {({ width }) => (
                    <List
                      width={width}
                      rowCount={count}
                      rowHeight={ROW_HEIGHT}
                      rowRenderer={this.rowRenderer}
                      height={height}
                      autoHeight
                      isScrolling={isScrolling}
                      scrollTop={scrollTop}
                      onRowsRendered={onRowsRendered}
                      ref={registerChild}
                    />
                  )}
                </AutoSizer>
              )}
            </WindowScroller>
          )}
        </InfiniteLoader>
      </div>
    );
  }

  render() {
    return (
      <div className={styles.houseList}>
        <Flex className={styles.houseHeader}>
          <i
            className="iconfont icon-back"
            onClick={() => this.props.history.go(-1)}
          ></i>
          <SearchHeader
            className={styles.header}
            cityName={this.state.cityName}
          ></SearchHeader>
        </Flex>
        {/* 房屋导航 */}
        <Sticky height={40}>
          <Filter onFilter={this.onFilter}></Filter>
        </Sticky>

        {/* 房屋列表结构 */}
        {this.renderHouseList()}
      </div>
    );
  }
}
